//
//  HomePageViewController.m
//  WWTQ
//
//  Created by JP on 2018/10/27.
//  Copyright © 2018年 Jqert. All rights reserved.
//

#import "HomePageViewController.h"
#import "CityTableViewController.h"
#import "HPDetailTableViewController.h"

#import "SelectCityDetailModel.h"
#import "SelectCityModel.h"

#import <CoreLocation/CoreLocation.h>
#import "WWTQLocation.h"
#import <MJExtension.h>
#import "WHWeatherView.h"

@interface HomePageViewController () <UIScrollViewDelegate, HPDetailTVCDelegate, CLLocationManagerDelegate, WWTQLocationDelegate>

@property (nonatomic, strong) UIView *diyNavigationBar;
@property (nonatomic, strong) UIScrollView *contentScrollView;
@property (nonatomic, strong) UILabel *titleLabel; //当前城市名称
@property (nonatomic, strong) UIImageView *locationCity; //定位城市
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSArray *allCityArr; //选择所有城市的数组
@property (nonatomic, strong) NSArray *selectCityArr;//所有的可选城市
@property (nonatomic, strong) WWTQLocation *location;

@property (nonatomic, strong) WHWeatherView *weatherView;

@property (nonatomic, assign) NSInteger currentPage;

@property (nonatomic, assign) BOOL isSelect; //是否跳转第一个页面

@end

@implementation HomePageViewController

- (WWTQLocation *)location {
    if (!_location) {
        _location = [[WWTQLocation alloc] init];
        _location.delegate = self;
    }
    return _location;
}

- (NSArray *)allCityArr {
    if (!_allCityArr) {
        _allCityArr = [NSArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"AllCityArr"]];
    }
    return _allCityArr;
}

- (NSArray *)selectCityArr {
    if (!_selectCityArr) {
        _selectCityArr = [SelectCityModel mj_objectArrayWithFilename:@"CityName.plist"];
    }
    return _selectCityArr;
}

- (UIScrollView *)contentScrollView {
    if (!_contentScrollView) {
        _contentScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, ScreenW, ScreenH - SafeAreaTopHeight)];
        _contentScrollView.backgroundColor = [UIColor clearColor];
        _contentScrollView.contentSize = CGSizeMake(ScreenW, ScreenH - SafeAreaTopHeight);
        _contentScrollView.pagingEnabled = YES;
        _contentScrollView.delegate = self;
        _contentScrollView.showsHorizontalScrollIndicator = NO;
        _contentScrollView.showsVerticalScrollIndicator = NO;
    }
    return _contentScrollView;
}

- (UIView *)diyNavigationBar {
    if (!_diyNavigationBar) {
        _diyNavigationBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, SafeAreaTopHeight)];
        _diyNavigationBar.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    }
    return _diyNavigationBar;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = ZYT18Font;
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.text = @"呜呜天气";
        _titleLabel.textAlignment = 1;
    }
    return _titleLabel;
}

- (UIImageView *)locationCity {
    if (!_locationCity) {
        _locationCity = [[UIImageView alloc] init];
        _locationCity.clipsToBounds = YES;
        _locationCity.contentMode = UIViewContentModeScaleAspectFit;
        _locationCity.image = [UIImage imageNamed:@"dingweiCity"];
        _locationCity.hidden = YES;
    }
    return _locationCity;
}

- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] init];
        [_pageControl setValue:[UIImage imageNamed:@"pageControlDot"] forKeyPath:@"pageImage"];
        [_pageControl setValue:[UIImage imageNamed:@"pageControlCurrentDot"] forKeyPath:@"currentPageImage"];
        _pageControl.transform=CGAffineTransformScale(CGAffineTransformIdentity, 0.25, 0.25);
    }
    return _pageControl;
}

- (WHWeatherView *)weatherView {
    if (!_weatherView) {
        _weatherView = [[WHWeatherView alloc] init];
    }
    return _weatherView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initBase];
    
    [self setUpDiyNavigationBar];
    
    [self setUpScrollView];
    
    [self addNotification];
    
    //初次进入页面,调用定位
    [self locationBtnClick];
}

#pragma mark - 添加背景动画
- (void)initBase {
    self.currentPage = 0;
    self.isSelect = NO;
    
    self.weatherView.weatherBackImageView.frame = self.view.bounds;
    [self.view addSubview:self.weatherView.weatherBackImageView];
    
    self.weatherView.frame = self.view.bounds;
    [self.view addSubview:self.weatherView];
    
    [self changeWeatherView:0];
}

- (void)setUpDiyNavigationBar {
    [self.view addSubview:self.diyNavigationBar];
    
    [self.diyNavigationBar addSubview:self.titleLabel];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.diyNavigationBar);
//        make.size.mas_equalTo(CGSizeMake(200, 36));
        make.height.mas_equalTo(36);
        make.bottom.equalTo(self.diyNavigationBar).offset(-8);
    }];
    
    [self.diyNavigationBar addSubview:self.locationCity];
    [_locationCity mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.titleLabel.mas_right).offset(2);
        make.centerY.mas_equalTo(self.titleLabel);
        make.size.mas_equalTo(CGSizeMake(25, 25));
    }];
    
    [self.diyNavigationBar addSubview:self.pageControl];
    [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom);
        make.centerX.mas_equalTo(self.titleLabel);
        make.width.mas_equalTo(200);
        make.bottom.mas_equalTo(self.diyNavigationBar);
    }];
    
    UIButton *addCityBtn = [[UIButton alloc] init];
    [addCityBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [addCityBtn setBackgroundImage:[UIImage imageNamed:@"addCity.png"] forState:UIControlStateNormal];
    [self.diyNavigationBar addSubview:addCityBtn];
    [addCityBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.diyNavigationBar).offset(-15);
        make.centerY.mas_equalTo(self.titleLabel);
        make.size.mas_equalTo(CGSizeMake(25, 25));
    }];
    
    UIButton *locationBtn = [[UIButton alloc] init];
    [locationBtn addTarget:self action:@selector(locationBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [locationBtn setBackgroundImage:[UIImage imageNamed:@"dingwei"] forState:UIControlStateNormal];
    [self.diyNavigationBar addSubview:locationBtn];
    [locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.diyNavigationBar).offset(15);
        make.centerY.mas_equalTo(self.titleLabel);
        make.size.mas_equalTo(CGSizeMake(25, 25));
    }];
}

- (void)setUpScrollView {
    [self.view addSubview:self.contentScrollView];
    if (@available(iOS 11.0, *)) {
        self.contentScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [self setUpTableView:self.allCityArr.count];
}

- (void)setUpTableView:(NSInteger)index {
    [self removeAllChildViewControllers];
    
    //other setting
    self.contentScrollView.contentSize = CGSizeMake(ScreenW*index, ScreenH - SafeAreaTopHeight);
    self.pageControl.numberOfPages = index;
    if (self.allCityArr.count == 0) {
        self.titleLabel.text = @"呜呜天气";
    } else {
        NSDictionary *cityDict = self.allCityArr[0];
        self.titleLabel.text = cityDict[@"name"];
        //选中的城市
        if ([cityDict[@"name"] isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"locationCityName"]]) {
            _locationCity.hidden = NO;
        } else {
            _locationCity.hidden = YES;
        }
    }
    
    for (int i = 0; i < index; i ++) {
        HPDetailTableViewController *hpDetailVC = [[HPDetailTableViewController alloc] init];
        [self addChildViewController:hpDetailVC];
        
        hpDetailVC.tableView.frame = CGRectMake(ScreenW*i, 0, ScreenW, ScreenH - SafeAreaTopHeight);
        hpDetailVC.delegate = self;
        
        NSDictionary *cityDict = self.allCityArr[i];
        //城市code
        hpDetailVC.cityCode = cityDict[@"code"];
        //下标
        hpDetailVC.indexCity = i;
        hpDetailVC.allCityArr = self.allCityArr;
        if (self.isSelect && i == index - 1) {
            hpDetailVC.isSelect = YES;
        } else {
            hpDetailVC.isSelect = NO;
        }
        
        [self.contentScrollView addSubview:hpDetailVC.tableView];
    }
    self.isSelect = NO;
}

//移除所有子视图控制器
- (void)removeAllChildViewControllers{
    for (HPDetailTableViewController *vc in self.childViewControllers) {
        [vc willMoveToParentViewController:nil];
        [vc removeFromParentViewController];
    }
    [self.contentScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger currentPage = (int)(scrollView.contentOffset.x) / (int)(ScreenW);
    if (self.currentPage != currentPage) {
        self.pageControl.currentPage = currentPage;
        self.allCityArr = [NSArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"AllCityArr"]];
        NSDictionary *cityDict = self.allCityArr[currentPage];

        self.titleLabel.text = cityDict[@"name"];
        //选中的城市
        if ([cityDict[@"name"] isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"locationCityName"]]) {
            _locationCity.hidden = NO;
        } else {
            _locationCity.hidden = YES;
        }
        
        [self changeWeatherView:currentPage];
        self.currentPage = currentPage;
    }
}

#pragma mark - 修改背景图片
- (void)changeWeatherView:(NSInteger)index {
    if (self.allCityArr.count < 1) {
        self.weatherView.weatherBackImageView.image = [UIImage imageNamed:@"sunBg.jpg"];
        [self.weatherView showWeatherAnimationWithType:WHWeatherTypeSun];
    } else {
        self.allCityArr = [NSArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"AllCityArr"]];
        NSDictionary *dictCity = self.allCityArr[index];
        NSString *type = dictCity[@"type"];
        if ([type isEqualToString:@"晴"]) {
            self.weatherView.weatherBackImageView.image = [UIImage imageNamed:@"sunBg.jpg"];
            [self.weatherView showWeatherAnimationWithType:WHWeatherTypeSun];
        } else if ([type isEqualToString:@"多云"] || [type isEqualToString:@"阴"]) {
            self.weatherView.weatherBackImageView.image = [UIImage imageNamed:@"cloudBg.jpg"];
            [self.weatherView showWeatherAnimationWithType:WHWeatherTypeClound];
        } else if ([type isEqualToString:@"阵雨"] || [type isEqualToString:@"小雨"] || [type isEqualToString:@"中雨"] || [type isEqualToString:@"大雨"] || [type isEqualToString:@"大雨"] || [type isEqualToString:@"小雨-中雨"] || [type isEqualToString:@"中雨-大雨"] || [type isEqualToString:@"雨夹雪"]) {
            self.weatherView.weatherBackImageView.image = [UIImage imageNamed:@"thunderstormBg.jpg"];
            [self.weatherView showWeatherAnimationWithType:WHWeatherTypeRain];
        } else if ([type isEqualToString:@"雷阵雨"] || [type isEqualToString:@"暴雨"] || [type isEqualToString:@"大暴雨"] || [type isEqualToString:@"特大暴雨"] || [type isEqualToString:@"大雨-暴雨"] || [type isEqualToString:@"暴雨-大暴雨"] || [type isEqualToString:@"大暴雨-特大暴雨"]) {
            self.weatherView.weatherBackImageView.image = [UIImage imageNamed:@"thunderstormBg.jpg"];
            [self.weatherView showWeatherAnimationWithType:WHWeatherTypeRainLighting];
        } else if ([type isEqualToString:@"阵雪"] || [type isEqualToString:@"小雪"] || [type isEqualToString:@"中雪"] || [type isEqualToString:@"大雪"] || [type isEqualToString:@"暴雪"] || [type isEqualToString:@"小雪-中雪"] || [type isEqualToString:@"中雪-大雪"] || [type isEqualToString:@"大雪-暴雪"]) {
            self.weatherView.weatherBackImageView.image = [UIImage imageNamed:@"snowBg.jpg"];
            [self.weatherView showWeatherAnimationWithType:WHWeatherTypeSnow];
        } else {
            self.weatherView.weatherBackImageView.image = [UIImage imageNamed:@"sunBg.jpg"];
            [self.weatherView showWeatherAnimationWithType:WHWeatherTypeOther];
        }
    }
}

#pragma mark - addNotification
- (void)addNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveSelectCityNotification:) name:SELECTCITY object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveDeleteCityNotification:) name:DELETECITY object:nil];
}

-(void)receiveSelectCityNotification:(NSNotification *)infoNotification {
    NSDictionary *cityDic = [infoNotification userInfo];
    NSString *cityCode = [cityDic objectForKey:@"code"];
    NSString *cityName = [cityDic objectForKey:@"name"];
    DeLog(@"城市:%@ code: %@", cityName, cityCode);
    
    NSMutableArray *cityMutArr = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"AllCityArr"]];
    [cityMutArr addObject:cityDic];
    self.allCityArr = [NSArray arrayWithArray:cityMutArr];
    
    [[NSUserDefaults standardUserDefaults] setObject:self.allCityArr forKey:@"AllCityArr"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    self.isSelect = YES;
    [self setUpTableView:self.allCityArr.count];
    
    self.titleLabel.text = cityName;
    self.pageControl.currentPage = self.allCityArr.count - 1;
    self.currentPage = self.allCityArr.count - 1;
    [self.contentScrollView setContentOffset:CGPointMake(ScreenW * (self.allCityArr.count - 1), 0)];
    
    //添加完调用切换背景动画
    [self changeWeatherView:self.allCityArr.count - 1];
}

-(void)receiveDeleteCityNotification:(NSNotification *)infoNotification {
    NSDictionary *cityDic = [infoNotification userInfo];
    self.allCityArr = [NSArray arrayWithArray:cityDic[@"allCityArr"]];
    [self setUpTableView:self.allCityArr.count];
    self.pageControl.currentPage = 0;
    [self.contentScrollView setContentOffset:CGPointMake(0, 0)];
    self.currentPage = 0;
    
    //删除完调用切换背景动画
    [self changeWeatherView:0];
}

#pragma mark - 添加城市按钮点击事件
- (void)addBtnClick{
    CityTableViewController *cityVC = [[CityTableViewController alloc]init];
    //跳转到城市选择VC
    cityVC.allCityArr = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"AllCityArr"]];
    cityVC.image = self.weatherView.weatherBackImageView.image;
    [self.navigationController pushViewController:cityVC animated:YES];
}

#pragma mark - 定位按钮
- (void)locationBtnClick {
    [self.location beginUpdatingLocation];
}

#pragma mark - <HPDetailTVCDelegate>
- (void)sendScrollViewAlpha:(CGFloat)alpha {
    self.diyNavigationBar.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:alpha*0.8];
    self.contentScrollView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:alpha*0.7];
}

- (void)sendContentOffsetY:(CGFloat)offsetY {
    for (HPDetailTableViewController *vc in self.childViewControllers) {
        [vc.tableView setContentOffset:CGPointMake(0, offsetY)];
    }
}

- (void)sendIsFristSelect {
    [self changeWeatherView:self.allCityArr.count - 1];
}

#pragma mark - WWTQLocation delegate
- (void)locationDidEndUpdatingLocation:(Location *)location {
    //在此对需要的数据进行处理使用
    DeLog(@"省/直辖市：%@",location.locality);
    
    NSString *cityName = [location.locality substringToIndex:location.locality.length-1];
    for (NSDictionary *dict in self.allCityArr) {
        if ([dict[@"name"] isEqualToString:cityName]) {
            //选中的城市
            [[NSUserDefaults standardUserDefaults] setObject:cityName forKey:@"locationCityName"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            return ;
        }
    }
    NSMutableArray *resultArr = [[NSMutableArray alloc] init];
    for (SelectCityModel *model in self.selectCityArr) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains %@ or shortpinyin contains %@ or fullpinyin contains %@", cityName, cityName, cityName]; // name\pinYin\pinYinHead不是随便写的, 是模型中的属性; contains是包含后面%@这个字符串
        NSArray *arr = [model.citys filteredArrayUsingPredicate:predicate];
        [resultArr addObjectsFromArray:arr];
    }
    SelectCityDetailModel *detailModel = resultArr.firstObject;
    NSDictionary *cityDic = [NSDictionary dictionaryWithObjectsAndKeys:detailModel.code, @"code", detailModel.name, @"name", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:SELECTCITY object:nil userInfo:cityDic];
}

- (void)sentErrorLocation {
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"您没有开启定位功能" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertView addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertView animated:YES completion:nil];
}

#pragma mark - viewWillAppear && viewWillDisappear
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

#pragma mark - 修改状态栏颜色
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
